<template>
	<a-modal title="发货单入库" :width="1300" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
		@ok="handleSubmit" @cancel="handleCancel">

		<template slot="footer">
			<a-button key="back" @click="handleCancel">
				取消
			</a-button>
			<a-button key="submit" type="primary" @click="handleSubmit">
				确认入库
			</a-button>
		</template>

		<a-spin :spinning="confirmLoading">
			<a-form :form="form">
				<a-row>

					<a-col :span="12" v-show="false">
						<a-form-item label="订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入订单号"
								v-decorator="['orderNumber', { rules: [{ required: false, message: '请输入订单号！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="false">
						<a-form-item label="订单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入订单类型"
								v-decorator="['orderType', { rules: [{ required: true, message: '请输入订单类型！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="false">
						<a-form-item label="源引订单Id" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入源引订单Id"
								v-decorator="['sourceOrderId', { rules: [{ required: false, message: '请输入源引订单Id！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="24">
						<a-table ref="table" size="default" style="margin-bottom: 24px" :columns="columns"
							:data-source="tableDataSource" :pagination="false">

							<template slot="materialModelNumber" slot-scope="text, record">
								{{ record.material ? record.material.materialModelNumber : '' }}
							</template>
							<!-- <span slot="image" slot-scope="text">
								<image-preview :images="text" />
							</span> -->
							<span slot="image" slot-scope="text,record">
								<image-preview1 :images="text" :imageUrl="record.imageUrl" />
							</span>
							<template slot="operationNumber" slot-scope="text, record">
								<a-input v-model="record.operationNumber" placeholder="请输入数量" :disabled="true" />
							</template>

							<template slot="markAbnormal" slot-scope="text, record">
								<a-switch checked-children="是" un-checked-children="否" :defaultChecked="text == 1"
									:disabled="record.isFinish" class="scoped-switch"
									@change="handleChangeMarkAbnormal($event, record)" />
							</template>

							<template slot="file" slot-scope="text, record">
								<!-- {{ record.isFinish }} -->
								<a-upload v-if="!record.file" :disabled="record.isFinish" name="file" :multiple="false"
									:showUploadList="false" :action="`${$store.state.baseUrl}/sysFileInfo/upload`"
									@change="handleChangeForUpload($event, record)">
									<a>上传</a>
								</a-upload>
								<a v-else @click="() => { previewVisible = true; previewImage = record.file; }">查看</a>
							</template>

						</a-table>
					</a-col>

				</a-row>
			</a-form>
		</a-spin>
		<a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
			<img style="width: 100%" :src="imageURLFormat(previewImage)" />
		</a-modal>
	</a-modal>
</template>

<script>
import { addAllType, addSimple, page, listDetail } from '@/api/modular/main/emsorder/emsOrderManage'
import { listResult } from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import { STable } from '@/components'
import { ORDER_TYPE_ENUM } from '@/utils/util'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
	components: { FcUpload, STable },
	data() {
		return {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 5 }
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 15 }
			},
			labelColBlock: {
				xs: { span: 24 },
				sm: { span: 2 }
			},
			wrapperColBlock: {
				xs: { span: 24 },
				sm: { span: 20 }
			},
			visible: false,
			confirmLoading: false,
			form: this.$form.createForm(this),
			fileList: [],
			tableDataSource: [],
			orderMaterials: [],
			orgIdSupplier: 'all',
			supplierList: [],
			columns: [
				{
					title: '序号', width: '80px',
					dataIndex: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '物料',
					dataIndex: 'materialName',
					// ellipsis: true,
				},
				{
					title: '料号',
					dataIndex: 'materialCode',
					// ellipsis: true,
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					scopedSlots: { customRender: 'materialModelNumber' }
				},
				{
					title: '图片',
					dataIndex: 'image',
					scopedSlots: { customRender: 'image' }
				},
				// {
				//   title: '采购单号',
				//   dataIndex: 'orderNumber',
				// },
				{
					title: '供应商发货数量',
					dataIndex: 'number',
					// scopedSlots: {customRender: 'number'}
				},
				{
					title: '已入数量',
					dataIndex: 'completedNumber',
				},
				{
					title: '实收数量',
					dataIndex: '',
					scopedSlots: { customRender: 'operationNumber' }
				},
				{
					title: '是否异常',
					dataIndex: 'markAbnormal',
					scopedSlots: { customRender: 'markAbnormal' }
				},
				{
					title: '入库图片',
					dataIndex: 'file',
					scopedSlots: { customRender: 'file' }
				},
			],
			previewVisible: false,
			previewImage: '',
			record: null,
			isFirstSubmit: null
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
	},
	methods: {
		show(record) {
			this.visible = true
			this.record = record
			setTimeout(() => {
				this.loadData()
			}, 100)
		},
		loadData() {
			this.confirmLoading = true
			this.tableDataSource = []
			// 由于从这个方法中进入的功能属于发货单转入库仓库，硬写一下
			this.form.setFieldsValue({
				orderType: this.$businessEnum.ORDER_TYPE_ENUM.inOrder.id,
				sourceOrderId: this.record.orderId
			})
			listResult({ orderId: this.record.orderId }).then(res => {
				res.data.forEach((currentValue) => {
					currentValue.operationNumber = currentValue.completedNumber
					currentValue.isFinish = currentValue.markAbnormal == 0
				})
				this.tableDataSource = res.data
			}).finally(() => {
				this.confirmLoading = false
			})
		},
		handleSubmit() {
			const { form: { validateFields } } = this
			this.confirmLoading = true

			validateFields((errors, values) => {
				if (!errors) {
					// 将表中的物料记录转成订单物料记录
					let _orderMaterials = this.tableDataSource.map(values => {
						let {
							orderNumber,
							operationNumber,
							orderMaterialId,
							orderId,
							sourceOrderId,
							sourceOrderMaterialId,
							bomId,
							materialId,
							number,
							completedNumber,
							executeStatus,
							executeProgress,
							file,
							remark,
							markAbnormal,
							status,
							createTime,
							createUser,
							updateTime,
							updateUser,
							materialName,
							materialCode,
							image,
						} = values
						// 接口其实只要某几个数据就好了,其它都是多余的
						return {
							// orderMaterialId: '',
							// orderId: '',
							sourceOrderId: orderId,
							cgSourceOrderId: sourceOrderId,
							sourceOrderMaterialId: orderMaterialId,
							bomId: bomId,
							materialId: materialId,
							number: operationNumber,
							// completedNumber: '',
							// executeStatus: '',
							// executeProgress: '',
							file: file,
							// remark: '',
							markAbnormal: markAbnormal,
							// status: '',
							// createTime: '',
							// createUser: '',
							// updateTime: '',
							// updateUser: '',
						}
					})

					values.orderMaterials = _orderMaterials
					// 本页面暂时只有发货单（由数个采购单生成）和收货单（由单个发货单生成）进入操作。订单类型由进入页面的代码来管理
					addAllType(values).then((res) => {
						this.confirmLoading = false
						if (res.success) {
							this.$message.success('新增成功')
							this.handleCancel()
							this.$emit('ok', values)
						} else {
							this.$message.info('新增失败：' + res.message)
						}
					}).finally((res) => {
						this.confirmLoading = false
					})
					// }
				} else {
					this.confirmLoading = false
				}
			})
		},
		handleCancel() {
			this.form.resetFields()
			this.visible = false
		},
		// upload
		uploadChange(fileListString) {
			this.form.setFieldsValue({ file: fileListString })
		},
		// supper
		// switch
		handleChangeMarkAbnormal(checked, record) {
			record.markAbnormal = checked ? 1 : 0
			record.operationNumber = record.number
		},
		handleChangeForUpload(event, record) {
			// console.log('handleChangeForUpload - record:'+JSON.stringify(record))
			// console.log('handleChangeForUpload:' + JSON.stringify(event))
			let eventFile = event.file
			if (eventFile.status == 'done') {
				// TODO 上传成功，赋值
				const resultFile = eventFile.response.data
				record.file = resultFile
			}
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		}
	},
}
</script>
<style scoped>
.scoped-switch.ant-switch {
	background-color: #1890FF !important;
}

.scoped-switch.ant-switch-checked {
	background-color: #ff4d4f !important;
}
</style>
